﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;


namespace LazyFun
{
    public class PathParser : Singleton<PathParser>
    {
        #region Dllreference

        [System.Runtime.InteropServices.DllImport("shell32.dll")]
        private static extern int ExtractIconEx(string lpszFile, int niconIndex, IntPtr[] phiconLarge, IntPtr[] phiconSmall, int nIcons);

        #endregion

        const string _exe_everything_path = "Everything.exe";
        const string _fullpath_path = "./fullPath.txt";
        public const string _appinfo_path = "./app.dat";
        public const string _image_path = "./images";

        Dictionary<int, CustomProgramInfo> _dic_custom_program_info;
        List<string> _allpaths;
        List<AppInfomation> _exe_path = new List<AppInfomation>();
        Dictionary<string, AppInfomationEx> _dic_version = new Dictionary<string, AppInfomationEx>();

        public void StartPraser()
        {
            //获取所有路径
            if (File.Exists(_fullpath_path)) File.Delete(_fullpath_path);

            List<string> results = EverythingHelper.StartEverythingSearch(".exe", _exe_everything_path);
            File.WriteAllLines(_fullpath_path, results.ToArray());

            //初始化
            _dic_custom_program_info = ExcelUtil.LoadCsvData<CustomProgramInfo>("./CustomProgramInfo.xls");

            string[] lines = File.ReadAllLines(_fullpath_path);
            this._allpaths = lines.ToList();
            for (int i = 0; i < _allpaths.Count; i++)
            {
                _allpaths[i] = _allpaths[i].Replace("\\", "/");
                string exename = FileTools.GetFullName(_allpaths[i]);
                foreach (var item in _dic_custom_program_info.Values)
                {
                    if (item.program_end_prefix == exename)
                    {
                        AppInfomation info = new AppInfomation();
                        info._custom_app_name = item.custom_app_name;
                        info._exe_name = item.program_end_prefix;
                        info._group_name = item.cap;
                        info._fullpath = _allpaths[i];
                        info._help_tip = item.tip;

                        //架构 0:区分 1：不区分
                        if (item.is_care_structure == 0)
                        {
                            ushort code = ExplorerUtil.GetPEArchitecture(info._fullpath);
                            info._architecture = code == 0x10b?0:1;
                        }

                        //文件版本
                        FileVersionInfo fileversion = FileVersionInfo.GetVersionInfo(info._fullpath);
                        AppInfomationEx ex = new AppInfomationEx();
                        ex.app_info = info;
                        ex.fileversion = fileversion;

                        if (item.is_care_version == 0)
                        {
                            string _custom_app_name = info._custom_app_name;
                            if (_dic_version.ContainsKey(_custom_app_name))
                            {
                                if (fileversion.FileMajorPart >= _dic_version[_custom_app_name].fileversion.FileMajorPart   //Main
                                    && fileversion.FileMinorPart >= _dic_version[_custom_app_name].fileversion.FileMinorPart    //Mirror
                                    && fileversion.FileBuildPart >= _dic_version[_custom_app_name].fileversion.FileBuildPart)   //Build
                                {
   
                                    _dic_version[_custom_app_name] = ex;
                                }
                            }
                            else
                            {
                                _dic_version.Add(_custom_app_name, ex);
                            }

                        }
                        else
                        {
                            info._version_info = string.Format("{0}_{1}_{2}", fileversion.FileMajorPart, fileversion.FileMinorPart, fileversion.FileBuildPart);
                            _exe_path.Add(info);
                        }
                    }
                }
            }

            //添加需要筛选版本的信息
            if (_dic_version.Count > 0)
            {
                foreach (var item in _dic_version.Values)
                {
                    item.app_info._version_info = string.Format("{0}_{1}_{2}", item.fileversion.FileMajorPart, item.fileversion.FileMinorPart, item.fileversion.FileBuildPart);
                    _exe_path.Add(item.app_info);
                }
            }

            //生成图标
            //获取应用程序图标并保存
            string path = "";
            try
            {
                foreach (AppInfomation appInf in _exe_path)
                {
                    System.Drawing.Bitmap bitmap = ExplorerUtil.GetIconByFileName(appInf._fullpath, true).ToBitmap();
                    if (bitmap != null)
                    {
                        if (!Directory.Exists(_image_path)) Directory.CreateDirectory(_image_path);
                        path = string.Format("{0}/{1}.png", _image_path, appInf._custom_app_name);
                        if (File.Exists(path)) File.Delete(path);
                        bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png);

                        appInf._icon_path = path;
                    }
                }
            }
            catch { }

            //序列化
            AppInfos infos = new AppInfos();
            infos.info_list = _exe_path;
            byte[] bytes = SerializeHelper.SerializeToBinary(infos);
            File.WriteAllBytes(_appinfo_path, bytes);
        }
    }
}
